package com.xiaoyu.lanling.view.text

import android.content.Context
import android.text.InputFilter
import android.text.InputFilter.LengthFilter
import android.text.TextUtils
import android.util.AttributeSet
import android.widget.TextView
import androidx.emoji.widget.EmojiTextView
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.UserNameUpdateEvent
import com.xiaoyu.base.model.User
import com.xiaoyu.base.utils.extensions.getViewTag
import com.xiaoyu.base.utils.extensions.setViewTag
import com.xiaoyu.lanling.common.Constant
import org.greenrobot.eventbus.Subscribe

class UserNameTextView : EmojiTextView {

    constructor(context: Context?) : super(context) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    private fun init() {
        // final int maxLength = RemoteConfigClient.getInstance().getInt("features.user.nickname_max_length", 14);
        filters = arrayOf<InputFilter>(LengthFilter(10))
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        AppEventBus.getInstance().register(this)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        AppEventBus.getInstance().unregister(this)
    }

    @Subscribe
    fun onEvent(event: UserNameUpdateEvent) {
        val uid: String? = getViewTag(Constant.GlobalViewTagDefine.VIEW_TAG_FOR_UID)
        if (TextUtils.equals(uid, event.user.uid)) {
            post { text = event.user.remark }
        }
    }

    fun setUser(user: User) {
        text = user.remark
        setViewTag(Constant.GlobalViewTagDefine.VIEW_TAG_FOR_UID, user.uid)
    }
}